package cn.donting.web.desktop.plugin.test;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import org.springframework.boot.loader.tools.JarWriter;
import org.springframework.boot.loader.tools.Library;

import java.io.File;
import java.io.IOException;

public class BuildSys {

    public File file;
    public  File unzipDir;

    public BuildSys(File file) {
        this.file = file;
    }

    public void build() throws IOException {
         unzipDir = ZipUtil.unzip(file);
        File libs = new File(unzipDir.getPath() + File.separator + "BOOT-INF" + File.separator + "lib");
        //拷贝 servlet-api ,top
        for (File lib : libs.listFiles()) {
            if (lib.getName().contains("jakarta.servlet-api-")
                    || lib.getName().contains("web-desktop-top-")) {
                File file1 = new File(unzipDir.getPath() + File.separator + lib.getName());
                FileUtil.move(lib, file1, true);
                File unzip = ZipUtil.unzip(file1);
                for (File listFile : unzip.listFiles()) {
                    if (!listFile.getName().equals("META-INF")) {
                        FileUtil.move(listFile, unzipDir, true);
                    }
                }
                FileUtil.del(unzip);
                file1.delete();
            }
        }

        //再次生产 jar
        File file1 = new File(file.getParentFile() + File.separator + "copy.jar");
        JarWriter jarWriter = new JarWriter(file1);
        zip(jarWriter,unzipDir);
        jarWriter.close();
    }


    private void zip(JarWriter jarWriter, File file) throws IOException {
        if(file.isFile()){
            String location = getLocation(file).substring(1);
            jarWriter.writeNestedLibrary(location, new Library(file, null));
        }else {
            for (File listFile : file.listFiles()) {
                zip(jarWriter,listFile);
            }
        }
    }

    public String getLocation(File file){
        if(file.getPath().equals(unzipDir.getPath())){
            return "";
        }else{
            return getLocation(file.getParentFile())+"/"+file.getName();
        }
    }



    public static void main(String[] args) throws IOException {
        BuildSys buildSys = new BuildSys(new File("D:\\新建文件夹\\web-desktop\\web-desktop-sys\\build\\libs\\web-desktop-sys-0.0.1-SNAPSHOT.jar"));
        buildSys.build();


    }

}
